<template>
<el-card id="tableGrid" shadow="never" style="margin: 15px 0;">
<div>
  <div key="toolbar" v-if="toolbar" id="tableToolbar" style="margin-bottom: 10px">
    <template v-for="(tool, index) in toolbar">
      <custom-btn :id="tool.type" :btnType="tool.type" :label="_$Z[tool.label]" :disabled="tool.disabled?tool.disabled:false" @btn-click="(()=>toolbarClick(tool.method))" :key="'set' + index"></custom-btn>
    </template>
  </div>

  <el-table 
    key="dataTable"
    v-loading="loading"
    :border="true"
    :row-class-name="tableRowClass"
    :header-cell-class-name="tableHeadClass"
    ref="multipleTable"
    :data="tableData"
    :summary-method="getSummaries"
    :show-summary="isNeedSummary"
    tooltip-effect="dark"
    @selection-change="setSelections"
    @row-click="rowClick"
    :default-sort = "{order: 'descending'}"
    highlightCurrentRow>
    <el-table-column v-if="isNeedCheckBox"
                     type="selection"
                     key="isNeedCheckBox"
                     width="40">
    </el-table-column>
    <el-table-column v-if="isNeedRadioBox"
                    key="isNeedRadioBox"
                     width="40"
                     :show-overflow-tooltip="false">
      <template slot-scope="scope">
        <el-radio class="radio" v-model="radio" :label="scope.$index" @change.native="setSelected(scope.row)"></el-radio>
      </template>
    </el-table-column>

    <el-table-column  key="expand" v-if="expand" type="expand" width="40" class="table-expand">
      <template slot-scope="props">
        <div class="demo-table-expand">
          <el-form  inline>
          <template v-for="cdata in columnData">
            <el-form-item v-if="cdata.prop&&cdata.prop!=='operations'" :label="_$Z[cdata.label]" :key="cdata.label">              
              <div style="font-size:12px">
                <span>{{props.row[cdata.prop]}}</span>
              </div>
            </el-form-item>
          </template>
          </el-form>
        </div>
      </template>
    </el-table-column>

    <template v-for="cdata in columnData">
      <!-- vue认为key相同的情况下，如果变更，不进行刷新，所以在key上面加了个随机数 -->
      <table-column v-if="!cdata.ishide" :key="cdata.prop+Math.random()" :column-data="cdata"></table-column>
    </template>

  </el-table>
 
  <div id="footer" style="padding-top: 10px;" v-if="showFooter">
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="page"
      :page-sizes="[10, 20, 30, 50, 100, 200, 500]"
      :page-size="10"
      :pager-count="footer.pagerCount"
      background
      :layout="footer.layout"
      :total="total"
      style="display: inline-block;">
    </el-pagination>

    <el-dropdown split-button type="primary" v-if="suportExport" @command="exportData" style="position: absolute; padding-top: 1px;">
      <i class="iconfont icon-export" style="font-size:12px"></i>
      <el-dropdown-menu slot="dropdown">
        <!-- <el-dropdown-item command='currentPDF'><i class="iconfont icon-ePDF"     style="font-size:15px;margin-right: 3px;color:#FF0000"></i>{{_$Z['excel_menu_text']}}</el-dropdown-item>
        <el-dropdown-item command='allPDF'><i class="iconfont icon-ePDF"         style="font-size:15px;margin-right: 3px;color:#FF0000"></i>{{_$Z['excel_menuAll_text']}}</el-dropdown-item> -->
        <el-dropdown-item command='currentExcel'><i class="iconfont icon-eExcel" style="font-size:15px;margin-right: 3px;color:#1d8bd8"></i>{{_$Z['excel_menu_text']}}</el-dropdown-item>
        <el-dropdown-item command='allExcel'><i class="iconfont icon-eExcel"     style="font-size:15px;margin-right: 3px;color:#1d8bd8"></i>{{_$Z['excel_menuAll_text']}}</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</div>
</el-card>
</template>

<style lang="scss">
  .radio {
    vertical-align: middle;
    .el-radio__label {
      display: none;
    }
  }

  .table-expand .el-table, .el-table__expanded-cell{
    background-color:#ebf4fd;
  }
  .table-expand .el-table, .el-table__expanded-cell[class*=cell]{
    padding: 15px 20px;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 5px;
    width: 33%;
    .el-form-item__label {
      font-size: 12px;
      width: 180px;
      color:$blue-btn;
      line-height: 15px
    }
    .el-form-item__content, .el-form-item__label{
      line-height: 15px
    }
   }
</style>

<script>
import { query, exportFile } from '@/api/common'
import fileDownload from 'js-file-download'
import tableColumn from './tableColumn'
import { deepClone } from '@/utils/index'
export default {
  name: 'customTableGrid',
  components: { tableColumn },
  data() {
    return {
      start: 1,
      limit: 10,
      page: 1,
      tableData: [],
      total: 0,
      multipleSelection: [],
      i18Keys: [],
      showFooter: false,
      queryParam: null,
      loading: false,
      radio: ''
    }
  },
  props: {
    url: {
      type: String,
      required: true
    },
    suportExport: {
      type: Boolean,
      default: true
    },
    title: {
      type: String, // 导出的文件名称前缀
      default: () => 'exportFile'
    },
    expand: {
      type: Boolean,
      default: false
    },
    isNeedCheckBox: { // 是否需要复选框
      type: Boolean,
      required: false,
      default: false
    },
    isNeedRadioBox: { // 是否需要单选框
      type: Boolean,
      required: false,
      default: false
    },
    isNeedSummary: { // 是否需要合计列
      type: Boolean,
      required: false
    },
    needEmitTableData: {
      type: Boolean,
      default: false
    },
    toolbar: {
      type: Array,
      required: false
    },
    footer: { // 自定义分页, 如：footer = {pagerCount: 5(大于等于 5 且小于等于 21 的奇数), layout: 'total'}
      type: Object,
      default: function() {
        return {
          pagerCount: 11,
          layout: 'total, sizes, prev, pager, next'
        }
      }
    },
    columnData: {
      type: Array,
      required: true,
      validator: function(value) {
        let result = true
        value.forEach(element => {
          if (element.label) {
            result = true
          } else {
            result = false
          }
          if (element.prop) {
            result = true
          } else {
            result = false
          }
          if (!element.sort) {
            element.sort = false
            result = true
          } else {
            result = true
          }
          if (!element.width) {
            result = true
          } else {
            result = true
          }
          if (['left', 'center', 'right'].indexOf(element.align) === -1) {
            element.align = 'left'
            result = true
          } else {
            result = true
          }
          if (!element.ishide) {
            element.ishide = false
            result = true
          } else {
            element.ishide = true
            result = true
          }
        })
        return result
      }
    }
  },
  methods: {
    initI18Keys() {
      const i18Keys = ['summary', 'excel_menu_text', 'excel_menuAll_text']
      this.addI18(this.columnData, i18Keys)
      if (this.toolbar) {
        this.toolbar.forEach(element => {
          i18Keys.push(element.label)
        })
      }
      this.i18Keys = i18Keys
    },
    addI18(columnData, i18Keys) {
      columnData.forEach(element => {
        i18Keys.push(element.label)
        if (element.children) {
          this.addI18(element.children, i18Keys)
        }
      })
    },
    rowClick(row, event, column) {
      this.$emit('row-click', row)
    },
    exportData(command) {
      this.loading = true
      const exportParam = {
        'excel.gridTitle': this.title,
        'excel.gridHeaders': this.getHeader(),
        'isExcel': command.indexOf('PDF') >= 0 ? 'PDF' : 'Excel',
        'start': command.indexOf('all') >= 0 ? 0 : this.start,
        'limit': command.indexOf('all') >= 0 ? 100000 : this.limit
      }

      const param = Object.assign(deepClone(this.queryParam), exportParam)
      exportFile(this.url, param).then(response => {
        let fileName
        if (command.indexOf('Excel') >= 0) {
          fileName = response.headers['content-disposition'].match(/filename=(\S*)xls/)[0].replace('filename=', '')
        } else if (command.indexOf('PDF') >= 0) {
          fileName = response.headers['content-disposition'].match(/filename=(\S*)pdf/)[0].replace('filename=', '')
        }
        fileDownload(response.data, fileName)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getHeader() {
      const columns = this.columnData
      const headers = ['{']
      columns.forEach(element => {
        if (element.type !== 'operations') {
          headers.push("'" + element.prop + "'")
          headers.push(':', "'", this._$Z[element.label] + '@#@show', "'")
          headers.push(',')
        }
      })
      if (headers.length > 0) {
        headers.splice(headers.length - 1, 1)
      }
      headers.push('}')
      return headers.join('')
    },
    tableHeadClass(data) { // 设置表头样式
      if (data.column.property) {
        return data.column.property + ' grid-header'
      } else {
        return 'grid-header'
      }
    },
    tableRowClass({ row, rowIndex }) { // 设置表内样式 - 斑马纹
      if (rowIndex % 2 === 0) {
        return 'grid-row'
      }
      return ''
    },
    setSelected(val) { // 设置单选
      this.multipleSelection = val
    },
    setSelections(val) { // 设置多选
      this.multipleSelection = val
    },
    getSelected() { // 获取单选行
      return this.multipleSelection
    },
    getSelections() { // 获取多选行
      return this.multipleSelection
    },
    handleSizeChange(val) { // 每页展示数改变时
      this.limit = val
      this.start = 1
      this.setPage()
    },
    handleCurrentChange(val) { // 当前页改变时
      this.start = (val - 1) * this.limit + 1
      this.setPage()
    },
    setPage() { // 设置页码
      this.queryParam['start'] = this.start
      this.pageQuery(this.queryParam)
    },
    pageQuery(param) { // 查询
      this.loading = true
      this.queryParam = param
      this.multipleSelection = []
      this.radio = ''
      if (!param.start) {
        this.queryParam['start'] = 1
        this.page = 1
      }
      this.queryParam['limit'] = this.limit
      query(this.url, param).then(response => {
        this.loading = false
        const data = response.data.data
        if (data) {
          this.tableData = data.result

          this.total = data.rows
          if (this.needEmitTableData) {
            this.$emit('rowsdata', this.tableData)
          }
        }
      }).catch(() => {
        this.loading = false
      })
    },
    clearResult() { // 清除结果集
      this.tableData = []
    },
    getSummaries(param) { // 获取合计值
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this._$Z['summary']
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = 'N/A'
        }
      })
      return sums
    },

    toolbarClick(callback) {
      callback(this.multipleSelection)
    }

  },
  created() {
    this.initI18Keys()
  },
  watch: {
    tableData(value) {
      if (value.length === 0 || value.length === '0') {
        this.showFooter = false
      } else if (value.length >= 0) {
        if (this.footer !== null) {
          this.showFooter = true
        }
      }
    },
    columnData() {
      this.initI18Keys()
    },
    toolbar() {
      this.initI18Keys()
    }
  }
}
</script>
